202511302354 如何使用 unixsocket 进行 http 请求

202511302354 如何使用 unixsocket 进行 http 请求

当 HTTP 请求需要通过本地 Unix Domain Socket 进行通信时,URL 的写法取决于你使用的工具或库。以下是几种常见场景:

1. 使用 curl

# 基本格式
curl --unix-socket /path/to/socket.sock http://localhost/api/endpoint

# 示例:Docker API
curl --unix-socket /var/run/docker.sock http://localhost/containers/json

2. 使用 Node.js

const http = require('http');

const options = {
  socketPath: '/path/to/socket.sock',
  path: '/api/endpoint',
  method: 'GET'
};

const req = http.request(options, (res) => {
  // 处理响应
});

3. 使用 Python requests

import requests
from requests.adapters import HTTPAdapter
from requests_unixsocket import UnixAdapter

session = requests.Session()
session.mount('http+unix://', UnixAdapter())

# URL 格式:http+unix://<encoded_socket_path>/<path>
response = session.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/containers/json')

4. 使用 wget

wget --method=GET --unix-socket=/path/to/socket.sock http://localhost/api/endpoint

关键点: